package com.sie.plm.rpm.standar.service.project.impl;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.text.CharSequenceUtil;
import cn.hutool.core.util.ObjectUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.hustcad.plm.rpm.mapper.org.GroupMapper;
import com.hustcad.plm.rpm.model.dto.active.ImportActiveDTO;
import com.hustcad.plm.rpm.model.dto.admin.ProjectDTO;
import com.hustcad.plm.rpm.model.dto.remote.CheckRemoteParams;
import com.hustcad.plm.rpm.model.dto.remote.RemoteDetialInfoDTO;
import com.hustcad.plm.rpm.model.dto.team.ImportTeamDTO;
import com.hustcad.plm.rpm.model.dto.team.TeamTree4InsertRoleDTO;
import com.hustcad.plm.rpm.model.dto.team.TeamTreeDTO;
import com.hustcad.plm.rpm.model.entity.admin.Project;
import com.hustcad.plm.rpm.model.entity.admin.ProjectRemoteLink;
import com.hustcad.plm.rpm.model.entity.org.Group;
import com.hustcad.plm.rpm.model.entity.org.User;
import com.hustcad.plm.rpm.model.entity.plan.Plan;
import com.hustcad.plm.rpm.model.vo.admin.ProjectVO;
import com.hustcad.plm.rpm.service.admin.ProjectService;
import com.hustcad.plm.rpm.service.forpdm.admin.ProjectServiceForPdm;
import com.hustcad.plm.rpm.service.importdata.ImportDataService;
import com.hustcad.plm.rpm.service.org.UserService;
import com.hustcad.plm.rpm.service.plan.PlanService;
import com.hustcad.plm.rpm.service.remote.RemoteObjectInfoService;
import com.hustcad.plm.rpm.service.team.ContainerTeamService;
import com.hustcad.plm.rpm.service.team.ProjectTeamService;
import com.hustcad.plm.rpm.util.SessionUtils;
import com.hustcad.plm.rpm.util.beanmapper.BeanMapper;
import java.math.BigInteger;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.function.Function;
import java.util.stream.Collectors;

import com.sie.plm.rpm.standar.service.project.StandarProjectService;
import com.sie.plm.rpm.standar.service.third.ThirdApiService;
import com.sie.plm.rpm.standar.vo.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

@Service
public class StandarProjectServiceImpl implements StandarProjectService {
    private static final Logger log = LoggerFactory.getLogger(StandarProjectServiceImpl.class);


    @Value("${tysoft.createFolder:remote}")
    private String createFolder;


    @Value("${stander.sync.team:true}")
    private Boolean sync;


    @Autowired
    private ProjectServiceForPdm projectServiceForPdm;

    @Autowired
    private RemoteObjectInfoService remoteObjectInfoService;

    @Autowired
    private ThirdApiService thirdApiService;

    @Autowired
    private ContainerTeamService containerTeamService;

    @Autowired
    private ProjectService projectService;

    @Autowired
    private UserService userService;

    @Autowired
    private ProjectTeamService projectTeamService;

    @Autowired
    private GroupMapper groupMapper;

    @Autowired
    private ImportDataService importDataService;

    @Autowired
    private PlanService planService;

    @Transactional(rollbackFor = Exception.class)
    @Override
    public ProjectVO creatStandarProject(ProjectVO project) {
        ProjectDTO projectDTO, map = (ProjectDTO)BeanMapper.map(project, ProjectDTO.class);

        if ("local".equals(this.createFolder)) {
            projectDTO = this.projectServiceForPdm.insertProjectForPdmWithFolderPath(map);
        } else {
            projectDTO = this.projectServiceForPdm.insertProjectForPdmProduct(map);
        }
        log.info(JSON.toJSONString(projectDTO));

        if (Boolean.TRUE.equals(this.sync)) {

            List<MemberDTO> productManagerList = getProductManagerList(project);
            ImportActiveDTO projectTemplateObj = project.getProjectTemplateObj();
            Boolean resousceFalg = projectTemplateObj.getResousceFalg();

            Map<String, List<MemberDTO>> roleUserMap = new HashMap<>();
            if (Boolean.TRUE.equals(resousceFalg))
            {
                buildTemplateTeamData(productManagerList, project, roleUserMap);
            }
            String projectOid = projectDTO.getOid();

            syscRoleAndUser(productManagerList, roleUserMap, projectOid);
        }
        return project;
    }

    private void syscRoleAndUser(List<MemberDTO> productManagerList, Map<String, List<MemberDTO>> roleUserMap, String projectOid) {
        RemoteDetialInfoDTO remoteDetailInfoDto = getRemoteDetialInfoDTO(projectOid, "ty.inteplm.project.CTyProject", ProjectRemoteLink.class);

        String productOid = remoteDetailInfoDto.getRemoteMasteredId();
        String productObject = this.thirdApiService.getProductByOid(productOid);


        ProductVO productVO = (ProductVO)JSON.parseObject(productObject, ProductVO.class);
        String containerTeamTree = this.thirdApiService.getContainerTeamTree(productVO);

        List<TeamVO> teamVOS = JSON.parseArray(containerTeamTree, TeamVO.class);

        Map<String, TeamVO> productRoleAndUser = new HashMap<>();
        for (TeamVO teamVO : teamVOS) {
            productRoleAndUser.put(teamVO.getRolename(), teamVO);
        }
        List<String> def = new ArrayList<>();
        def.add("role");
        JSONObject jsonObject = this.thirdApiService.batchQueryDefByName(JSON.toJSONString(def));
        JSONObject role = jsonObject.getJSONObject("role");
        Set<String> keySet = role.keySet();
        ArrayList<String> strings = new ArrayList<>(keySet);
        String roleDefOid = strings.get(0);

        addProductManagerAndUser(productOid, productRoleAndUser, productManagerList, "PRODUCT MANAGER", "产品库经理", productRoleAndUser
                .containsKey("PRODUCT MANAGER"), roleDefOid);

        if (CollUtil.isNotEmpty(roleUserMap))
        {
            for (Map.Entry<String, List<MemberDTO>> entry : roleUserMap.entrySet()) {
                String key = entry.getKey();
                addProductManagerAndUser(productOid, productRoleAndUser, entry.getValue(), key, key, productRoleAndUser
                        .containsKey(key), roleDefOid);
            }
        }
    }

    private void addProductManagerAndUser(String productOid, Map<String, TeamVO> roleMap, List<MemberDTO> teamUserList, String roleName, String displayName, boolean isContains, String roleDefOid) {
        if (Boolean.TRUE.equals(Boolean.valueOf(isContains))) {

            TeamVO role = roleMap.get(roleName);
            List<TeamVO> children = role.getChildren();

            Map<String, TeamVO> productUserMap = (Map<String, TeamVO>)children.stream().collect(Collectors.toMap(TeamVO::getOid, Function.identity(), (a, b) -> a));
            Set<MemberDTO> addList = getMemberDTOS(teamUserList, productUserMap);

            addUserToRole(productOid, addList, roleName);
        } else {

            insertRole(productOid, teamUserList, roleName, displayName, roleDefOid);
        }
    }

    private void insertRole(String productOid, List<MemberDTO> teamUserList, String roleName, String displayName, String roleDefOid) {
        List<String> enumDefKeys = new ArrayList<>();
        enumDefKeys.add("role");
        String enumItemsMapWithSort = this.thirdApiService.getEnumItemsMapWithSort(JSON.toJSONString(enumDefKeys));
        if (CharSequenceUtil.isNotBlank(enumItemsMapWithSort) && !CharSequenceUtil.isEmptyOrUndefined(enumItemsMapWithSort)) {
            JSONObject jsonObject = JSON.parseObject(enumItemsMapWithSort);
            JSONArray role = jsonObject.getJSONArray("role");
            List<KeyValue> keyValues = JSON.parseArray(role.toJSONString(), KeyValue.class);

            Map<String, KeyValue> roleEnumMap = (Map<String, KeyValue>)keyValues.stream().collect(Collectors.toMap(KeyValue::getKey, Function.identity(), (a, b) -> a));

            if (!roleEnumMap.containsKey(roleName)) {
                RoleEnumDef roleEnumDef = new RoleEnumDef();
                roleEnumDef.setPoid(new BigInteger(roleDefOid));
                roleEnumDef.setInternalName(roleName);
                roleEnumDef.setDisplayName(displayName);

                this.thirdApiService.insertEnumerationItem(JSON.toJSONString(roleEnumDef));
            }

            addRoleAndUser(productOid, teamUserList, roleName);
        }
    }

    private void addRoleAndUser(String productOid, List<MemberDTO> teamUserList, String roleName) {
        AddRoleVo roleVo = new AddRoleVo();
        ProductVO product = new ProductVO();
        product.setOid(productOid);
        roleVo.setProduct(product);
        List<RoleVO> roleList = new ArrayList<>();
        RoleVO roles = new RoleVO();
        roles.setName(roleName);
        roles.setRolekey(roleName);
        roleList.add(roles);
        roleVo.setRoles(roleList);

        this.thirdApiService.addRole(JSON.toJSONString(roleVo));
        Set<MemberDTO> addList = getMemberDTOS(teamUserList, new HashMap<>());

        addUserToRole(productOid, addList, roleName);
    }

    private void addUserToRole(String productOid, Set<MemberDTO> userList, String roleName) {
        AddAndDelRoleInUserVO addMemberInRoleVO = new AddAndDelRoleInUserVO();
        addMemberInRoleVO.setContext(productOid);
        List<RoleMemberDTOS> roleMemberDTOS = new ArrayList<>();
        RoleMemberDTOS roleMemberDTO = new RoleMemberDTOS();
        roleMemberDTO.setCode(roleName);
        roleMemberDTO.setMemberDTOS(userList);
        roleMemberDTOS.add(roleMemberDTO);
        addMemberInRoleVO.setRoleMemberDTOS(roleMemberDTOS);
        this.thirdApiService.addMemberInRole(JSON.toJSONString(addMemberInRoleVO));
    }

    private Set<MemberDTO> getMemberDTOS(List<MemberDTO> teamUserList, Map<String, TeamVO> productUserMap) {
        Set<MemberDTO> addList = new HashSet<>();
        for (MemberDTO user : teamUserList) {

            if (!productUserMap.containsKey(user.getOid())) {
                addList.add(user);
            }
        }
        return addList;
    }

    private RemoteDetialInfoDTO getRemoteDetialInfoDTO(String oid, String otype, Class<ProjectRemoteLink> linkClass) {
        CheckRemoteParams checkRemoteParams = new CheckRemoteParams();
        checkRemoteParams.setRefLocalOID(oid);
        checkRemoteParams.setRefLocalOTYPE(otype);
        return this.remoteObjectInfoService.getRemoteDetailInfoDtoByLocalMasterObj(checkRemoteParams, linkClass);
    }

    private void buildTemplateTeamData(List<MemberDTO> productManagerList, ProjectVO project, Map<String, List<MemberDTO>> roleUserMap) {
        List<TeamTreeDTO> teamTreeDTOS = this.containerTeamService.queryContainerTeamByContainer(project
                .getPlanTemplateOID(), project.getPlanTemplateOTYPE());
        for (TeamTreeDTO teamTreeDTO : teamTreeDTOS) {
            String type = teamTreeDTO.getType();
            List<TeamTreeDTO> children = teamTreeDTO.getChildren();

            if ("ProjectAdministrators".equals(type) || "ProjectManager".equals(type)) {
                continue;
            }

            if (CollUtil.isNotEmpty(children)) {
                List<String> nameList = children.stream().map(TeamTreeDTO::getName).collect(Collectors.toList());
                String rolename = teamTreeDTO.getName();
                List<MemberDTO> roleUserList = listUserByName(nameList);
                List<MemberDTO> orDefault = roleUserMap.getOrDefault(rolename, roleUserList);
                roleUserList.addAll(orDefault);
                roleUserMap.put(rolename, roleUserList);
            }
        }
    }

    private List<MemberDTO> getProductManagerList(ProjectVO project) {
        User currentUser = SessionUtils.getCurrentUser();
        List<String> nameList = new ArrayList<>();
        nameList.add(currentUser.getName());
        nameList.add(project.getOwnerName());
        List<User> projectManagerList = project.getProjectManagerList();
        if (CollUtil.isNotEmpty(projectManagerList)) {
            for (User user : projectManagerList) {
                nameList.add(user.getName());
            }
        }
        return listUserByName(nameList);
    }

    private List<MemberDTO> listUserByName(List<String> nameList) {
        if (CollUtil.isEmpty(nameList)) {
            return new ArrayList<>();
        }
        String user = this.thirdApiService.listUserByName(JSON.toJSONString(nameList));
        List<MemberDTO> userList = JSON.parseArray(user, MemberDTO.class);
        if (CollUtil.isNotEmpty(userList)) {
            userList.stream().forEach(item -> item.setType("user"));
        }
        return userList;
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void deleteStandarProjectManager(Map<String, Object> pmMap) {
        this.projectService.deleteProjectManagerOrAdministrator(pmMap);
        String projectOid = pmMap.get("projectOid").toString();
        if (Boolean.TRUE.equals(this.sync) && !isTemplateProject(projectOid)) {
            String userOid = pmMap.get("userOid").toString();
            User user = (User)this.userService.selectOneByOID(userOid);
            String name = user.getName();
            List<String> nameList = new ArrayList<>();
            nameList.add(name);
            List<MemberDTO> roleUserList = listUserByName(nameList);
            if (CollUtil.isNotEmpty(roleUserList)) {
                MemberDTO memberDTO = roleUserList.get(0);
                userOid = memberDTO.getOid();
            }

            deleteTeamUserByProjectOID("user", projectOid, userOid, user.getName(), "PRODUCT MANAGER", null);
        }

    }

    private void deleteTeamUserByProjectOID(String type, String projectOID, String userOid, String userName, String roleName, List<String> roles) {
        RemoteDetialInfoDTO remoteDetialInfoDTO = getRemoteDetialInfoDTO(projectOID, "ty.inteplm.project.CTyProject", ProjectRemoteLink.class);

        String productOid = remoteDetialInfoDTO.getRemoteMasteredId();
        Map<String, TeamVO> roleMap = getRoleAndUserByProductOid(productOid);
        AddAndDelRoleInUserVO addAndDelRoleInUserVO = new AddAndDelRoleInUserVO();
        addAndDelRoleInUserVO.setContext(productOid);
        if ("user".equals(type)) {
            TeamVO orDefault = (TeamVO)roleMap.getOrDefault(roleName, null);
            if (orDefault != null && CollUtil.isNotEmpty(orDefault.getChildren())) {
                List<TeamVO> children = orDefault.getChildren();
                for (TeamVO child : children) {
                    if (child.getOid().equals(userOid)) {
                        Set<MemberDTO> memberDTOS = new HashSet<>();
                        memberDTOS.add(new MemberDTO("user", userName, userOid, "ty.inteplm.org.CTyUser"));

                        List<RoleMemberDTOS> roleMemberDTOS = new ArrayList<>();
                        RoleMemberDTOS roleMemberDTO = new RoleMemberDTOS();
                        roleMemberDTO.setCode(roleName);
                        roleMemberDTO.setMemberDTOS(memberDTOS);
                        roleMemberDTOS.add(roleMemberDTO);
                        addAndDelRoleInUserVO.setRoleMemberDTOS(roleMemberDTOS);
                    }

                }
            }
        } else if (CollUtil.isNotEmpty(roles)) {
            List<String> roleList = new ArrayList<>();
            roles.stream().map(item -> {
                if (roleMap.containsKey(item)) {
                    roleList.add(item);
                }
                return item;
            }).collect(Collectors.toList());
            addAndDelRoleInUserVO.setRoleList(roleList);
        }

        this.thirdApiService.deleteStandarProjectManager(JSON.toJSONString(addAndDelRoleInUserVO));
    }

    private Map<String, TeamVO> getRoleAndUserByProductOid(String productOid) {
        Map<String, TeamVO> roleMap = new HashMap<>();
        String productObject = this.thirdApiService.getProductByOid(productOid);
        ProductVO productVO = (ProductVO)JSON.parseObject(productObject, ProductVO.class);
        String containerTeamTree = this.thirdApiService.getContainerTeamTree(productVO);
        List<TeamVO> teamVOS = JSON.parseArray(containerTeamTree, TeamVO.class);
        for (TeamVO teamVO : teamVOS) {
            roleMap.put(teamVO.getRolename(), teamVO);
        }
        return roleMap;
    }

    private boolean isTemplateProject(String oid) {
        boolean result;
        Project project = (Project)this.projectService.selectOneByOID(oid);
        Integer isTemplate = project.getIsTemplate();

        if (isTemplate != null && isTemplate.intValue() != 0) {
            result = true;
        } else {
            result = false;
        }
        return result;
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void standarDeleteRoleAndUser(TeamTreeDTO teamTreeDTO) {
        this.containerTeamService.deleteTeamItemByContainer("", "", teamTreeDTO);
        String projectOid = teamTreeDTO.getProjectOID();
        if (Boolean.TRUE.equals(this.sync) && !isTemplateProject(projectOid)) {
            String otype = teamTreeDTO.getOtype();
            if ("ty.inteplm.org.CTyUser".equals(otype)) {
                List<String> nameList = new ArrayList<>();
                nameList.add(teamTreeDTO.getName());
                List<MemberDTO> roleUserList = listUserByName(nameList);
                if (CollUtil.isNotEmpty(roleUserList)) {
                    MemberDTO memberDTO = roleUserList.get(0);
                    teamTreeDTO.setOid(memberDTO.getOid());
                    teamTreeDTO.setName(memberDTO.getName());
                }
                deleteTeamUserByProjectOID("user", projectOid, teamTreeDTO.getOid(), teamTreeDTO.getName(), teamTreeDTO
                        .getGroupName(), null);
            } else {
                List<String> roles = new ArrayList<>();
                roles.add(teamTreeDTO.getName());
                deleteTeamUserByProjectOID("role", projectOid, teamTreeDTO.getOid(), teamTreeDTO.getName(), teamTreeDTO
                        .getGroupName(), roles);
            }
        }
    }
    @Transactional(rollbackFor = Exception.class)
    @Override
    public void standarInsertProjectManager(Map<String, Object> pmMap) {
        if (ObjectUtil.isNotNull(pmMap.get("projectOid")) && ObjectUtil.isNotNull(pmMap.get("userOid"))) {
            this.projectService.doInsertProjectManagerOrAdministrator(pmMap);

            String projectOid = pmMap.get("projectOid").toString();
            if (Boolean.TRUE.equals(this.sync) && !isTemplateProject(projectOid)) {
                List<MemberDTO> userList = new ArrayList<>();
                String userOid = pmMap.get("userOid").toString();
                User user = (User)this.userService.selectOneByOID(userOid);
                String name = user.getName();
                List<String> nameList = new ArrayList<>();
                nameList.add(name);
                List<MemberDTO> roleUserList = listUserByName(nameList);
                if (CollUtil.isNotEmpty(roleUserList)) {
                    MemberDTO memberDTO = roleUserList.get(0);
                    userOid = memberDTO.getOid();
                }
                userList.add(new MemberDTO("user", user.getName(), userOid, user.getOtype()));
                syscRoleAndUser(userList, new HashMap<>(), projectOid);
            }
        }
    }

    @Override
    public void standarInsertRoleAndUser(TeamTree4InsertRoleDTO data) {
        String containerOID = data.getContainerOID();
        String containerOTYPE = data.getContainerOTYPE();
        TeamTreeDTO teamTreeDTO = data.getTeamTreeDTO();
        String oid = teamTreeDTO.getOid();
        Group group = (Group)this.groupMapper.selectByPrimaryKey(oid);
        this.projectTeamService.insertRoleByContainerJAC(containerOID, containerOTYPE, data.getTeamTreeDTO());
        if (Boolean.TRUE.equals(this.sync) && !isTemplateProject(containerOID)) {
            List<TeamTreeDTO> children = teamTreeDTO.getChildren();
            RemoteDetialInfoDTO remoteDetailInfoDto = getRemoteDetialInfoDTO(containerOID, "ty.inteplm.project.CTyProject", ProjectRemoteLink.class);

            String productOid = remoteDetailInfoDto.getRemoteMasteredId();
            String productObject = this.thirdApiService.getProductByOid(productOid);
            ProductVO productVO = (ProductVO)JSON.parseObject(productObject, ProductVO.class);
            String containerTeamTree = this.thirdApiService.getContainerTeamTree(productVO);
            List<TeamVO> teamVOS = JSON.parseArray(containerTeamTree, TeamVO.class);
            Map<String, TeamVO> roleMap = new HashMap<>();
            for (TeamVO teamVO : teamVOS) {
                teamVO.getRolename();
                roleMap.put(teamVO.getRolename(), teamVO);
            }
            List<String> def = new ArrayList<>();
            def.add("role");
            JSONObject jsonObject = this.thirdApiService.batchQueryDefByName(JSON.toJSONString(def));
            JSONObject role = jsonObject.getJSONObject("role");
            Set<String> keySet = role.keySet();
            ArrayList<String> strings = new ArrayList<>(keySet);
            String roleDefOid = strings.get(0);
            List<String> nameList = (List<String>)children.stream().map(TeamTreeDTO::getName).collect(Collectors.toList());
            List<MemberDTO> productManagerList = listUserByName(nameList);

            if (group == null) {
                String name = teamTreeDTO.getName();
                String roleName = teamTreeDTO.getChildName();
                addProductManagerAndUser(productOid, roleMap, productManagerList, name, name, roleMap
                        .containsKey(name), roleDefOid);
                insertRoleByProduct(productOid, roleName, roleMap.containsKey(roleName), roleDefOid);
            } else {
                String name = group.getName();
                addProductManagerAndUser(productOid, roleMap, productManagerList, name, name, roleMap
                        .containsKey(name), roleDefOid);
            }
        }

    }

    private void insertRoleByProduct(String productOid, String roleName, boolean isContains, String roleDefOid) {
        if (Boolean.TRUE.equals(Boolean.valueOf(isContains))) {
            ProductVO product = new ProductVO();
            product.setOid(productOid);

            RoleVO roles = new RoleVO();
            roles.setName(roleName);
            roles.setRolekey(roleName);

            List<RoleVO> roleList = new ArrayList<>();
            roleList.add(roles);

            AddRoleVo roleVo = new AddRoleVo();
            roleVo.setProduct(product);
            roleVo.setRoles(roleList);
            this.thirdApiService.addRole(JSON.toJSONString(roleVo));
        } else {
            insertRole(productOid, new ArrayList<>(), roleName, roleName, roleDefOid);
        }
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void standarImportTeamByTemplate(ImportTeamDTO data) {
        this.projectTeamService.importTeamByTemplate(data);
        if (Boolean.TRUE.equals(this.sync) && !isTemplateProject(data.getCurProjectOID())) {
            List<MemberDTO> productManagerList = new ArrayList<>();
            Map<String, List<MemberDTO>> roleUserMap = new HashMap<>();
            String teamTemplateOID = data.getTeamTemplateOID();
            String teamTemplateOTYPE = data.getTeamTemplateOTYPE();
            ProjectVO projectVO = new ProjectVO();
            projectVO.setPlanTemplateOID(teamTemplateOID);
            projectVO.setPlanTemplateOTYPE(teamTemplateOTYPE);
            buildTemplateTeamData(productManagerList, projectVO, roleUserMap);
            syscRoleAndUser(productManagerList, roleUserMap, data.getCurProjectOID());
        }
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void standarImportPlanActiveByPlanTemplate(ImportActiveDTO data) {
        this.importDataService.importPlanActiveByPlanTemplate(data);
        Plan plan = (Plan)this.planService.selectOneByOID(data.getCurPlanOID());
        if (Boolean.TRUE.equals(this.sync) && !isTemplateProject(plan.getParentOID())) {
            List<MemberDTO> productManagerList = new ArrayList<>();
            Map<String, List<MemberDTO>> roleUserMap = new HashMap<>();
            String teamTemplateOID = data.getPlanTemplateOID();
            String teamTemplateOTYPE = data.getPlanTemplateOTYPE();
            ProjectVO projectVO = new ProjectVO();
            projectVO.setPlanTemplateOID(teamTemplateOID);
            projectVO.setPlanTemplateOTYPE(teamTemplateOTYPE);
            Boolean resousceFalg = data.getResousceFalg();
            if (Boolean.TRUE.equals(resousceFalg))
            {
                buildTemplateTeamData(productManagerList, projectVO, roleUserMap);
            }

            syscRoleAndUser(productManagerList, roleUserMap, plan.getParentOID());
        }
    }
    @Transactional(rollbackFor = Exception.class)
    @Override
    public void saveObjIBAInfo(ProjectIbaVO projectIbaVO) {
        this.thirdApiService.saveObjIBAInfo(JSON.toJSONString(projectIbaVO));

        if (Boolean.TRUE.equals(this.sync)) {
            syncIba(projectIbaVO, true);
        }
    }

    private void syncIba(ProjectIbaVO projectIbaVO, boolean iscreate) {
        BigInteger projectOid = projectIbaVO.getObjInfoDTO().getOid();
        Map<String, List<String>> ibaAttribute = projectIbaVO.getIbaAttribute();
        if (CollUtil.isNotEmpty(ibaAttribute) && !isTemplateProject(projectOid.toString())) {
            Project project = (Project)this.projectService.selectOneByOID(String.valueOf(projectOid));
            String category = project.getCategory();

            String projectTYpe = this.thirdApiService.getTypeByTypeName(category);
            JSONObject projectJsonObj = JSON.parseObject(projectTYpe);
            QueryIbaVO queryIbaVO = new QueryIbaVO();
            queryIbaVO.setTypeoid(new BigInteger(projectJsonObj.getString("oid")));
            queryIbaVO.setTypeotype(projectJsonObj.getString("otype"));
            queryIbaVO.setSystemName("productLib");
            String typeAttrMappingsBySystem = this.thirdApiService.getTypeAttrMappingsBySystem(JSON.toJSONString(queryIbaVO));

            List<AttributeMappingBaseVO> attributeDefMap = JSON.parseArray(typeAttrMappingsBySystem, AttributeMappingBaseVO.class);



            Map<String, AttributeMappingBaseVO> projectAttrMap = (Map<String, AttributeMappingBaseVO>)attributeDefMap.stream().filter(item -> !CharSequenceUtil.isBlank(item.getMappingname())).collect(Collectors.toMap(AttributeMappingBaseVO::getPdminnername, Function.identity(), (a, b) -> b));
            Set<Map.Entry<String, AttributeMappingBaseVO>> entries = projectAttrMap.entrySet();

            Map<String, List<String>> proIbaAttribute = new HashMap<>();
            for (Map.Entry<String, AttributeMappingBaseVO> entry : entries) {
                String key = entry.getKey();
                AttributeMappingBaseVO value = entry.getValue();
                if (ibaAttribute.containsKey(key)) {
                    proIbaAttribute.put(value.getMappingname(), ibaAttribute.get(key));
                }
            }

            if (CollUtil.isNotEmpty(proIbaAttribute)) {
                RemoteDetialInfoDTO remoteDetialInfoDTO = getRemoteDetialInfoDTO(projectOid.toString(), "ty.inteplm.project.CTyProject", ProjectRemoteLink.class);

                String productOid = remoteDetialInfoDTO.getRemoteMasteredId();
                IbaObjVO ibaObjVO = new IbaObjVO();
                ibaObjVO.setOid(new BigInteger(productOid));
                ibaObjVO.setOtype("ty.inteplm.product.CTyPDMLinkProduct");
                ibaObjVO.setLogicalIdentifier("ty.inteplm.product.CTyPDMLinkProduct");
                ProjectIbaVO proIbaVO = new ProjectIbaVO();
                proIbaVO.setIbaAttribute(proIbaAttribute);
                proIbaVO.setObjInfoDTO(ibaObjVO);
                if (iscreate) {
                    this.thirdApiService.saveObjIBAInfo(JSON.toJSONString(proIbaVO));
                } else {
                    this.thirdApiService.updateObjIBAInfo(JSON.toJSONString(proIbaVO));
                }
            }
        }
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void updateObjIBAInfo(ProjectIbaVO projectIbaVO) {
        this.thirdApiService.updateObjIBAInfo(JSON.toJSONString(projectIbaVO));
        if (Boolean.TRUE.equals(this.sync)) {
            syncIba(projectIbaVO, false);
        }
    }
}
